<!-- 进行申报 -->
<script setup>
import { useRouter } from 'vue-router';
import { onMounted, ref, reactive, nextTick } from 'vue';
import { Cell, CellGroup } from 'vant';
let map = ref(null);
//获取路由器对象
let router = useRouter();
/* 获取当前位置 */
let position = ref(null);
// 表单传递数据
let desc = ref(null);
let phone = ref(null);
let into = ref(1);
//组件挂载完毕
onMounted(() => {
  nextTick(() => {
    fetch('https://api.ipify.org?format=json')
      .then(response => response.json())
      .then(data => {
        const ip = data.ip;
        console.log('IP地址:', ip);

      })
      .catch(error => console.error('获取失败:', error));
    // 请求地理位置权限
    if ("geolocation" in navigator) {
      navigator.geolocation.getCurrentPosition(
        (position) => {
          // 成功获取位置
          const latitude = position.coords.latitude;  // 纬度
          const longitude = position.coords.longitude; // 经度
          const accuracy = position.coords.accuracy;  // 精度（米）
          console.log(`纬度: ${latitude}, 经度: ${longitude}, 精度: ${accuracy}米`);
          getPosition(`${latitude},${longitude}`)
        },
        (error) => {
          getPosition('')
          // 失败处理
          switch (error.code) {
            case error.PERMISSION_DENIED:
              console.error("用户拒绝了定位请求");
              break;
            case error.POSITION_UNAVAILABLE:
              console.error("无法获取位置信息");
              break;
            case error.TIMEOUT:
              console.error("请求超时");
              break;
          }
        },
        {
          enableHighAccuracy: true, // 是否尝试高精度模式（如GPS）
          timeout: 5000,            // 超时时间（毫秒）
          maximumAge: 0             // 缓存位置的最大年龄（0=不缓存）
        }
      );
    } else {
      getPosition('')
      console.error("浏览器不支持Geolocation API");
    }
  })

});
// 获取位置
const getPosition = (val) => {
  let url = '';
  if (val == '') {
    // 如果没有位置信息，则获取当前位置ip
    url += 'https://restapi.amap.com/v3/ip?key=' + encodeURIComponent('e7c66774df829650f20e0e59ac4a95df')
  } else {
    // 如果有位置信息，就经纬度查询
    url += 'https://restapi.amap.com/v3/assistant/coordinate/convert?locations=' + val + '&coordsys=gps&key=' + encodeURIComponent('e7c66774df829650f20e0e59ac4a95df')
  }

  // 先获取当前的用户位置
  fetch(url)
    .then(response => response.json())//解析为可读数据
    .then((pos) => {
      if (val == '') {
        // 如果是ip定位
        console.log(JSON.stringify(pos))
        let positiondata = pos
        var point1 = positiondata.rectangle.split(';')[0].split(',')[0];
        var point2 = positiondata.rectangle.split(';')[0].split(',')[1];
        // 给map通过ref赋值dom元素
        // 获取地图元素ref
        if (map.value) {
          var bMap = new BMapGL.Map(map.value);          // 创建地图实例 
          var point = new BMapGL.Point(point1, point2);  // 创建点坐标 
          bMap.centerAndZoom(point, 12);                 // 初始化地图，设置中心点坐标和地图级别
          bMap.enableScrollWheelZoom(true);              // 开启鼠标滚轮缩放
          /* 添加点坐标位置显示在地图上 */
          var marker = new BMapGL.Marker(point);
          bMap.addOverlay(marker);
          // 逆地址编码
          getGeoCoder(point1, point2)
        } else {
          console.error('Map element is not found');
        }
      } else {
        // 如果是获取经纬度定位（非高德转换为高德坐标）
        console.log(pos.locations)
        var point1 = pos.locations.split(',')[0]
        var point2 = pos.locations.split(',')[1]
        if (map.value) {
          var bMap = new BMapGL.Map(map.value);          // 创建地图实例 
          var point = new BMapGL.Point(point2, point1);  // 创建点坐标 
          bMap.centerAndZoom(point, 12);                 // 初始化地图，设置中心点坐标和地图级别
          bMap.enableScrollWheelZoom(true);              // 开启鼠标滚轮缩放
          /* 添加点坐标位置显示在地图上 */
          var marker = new BMapGL.Marker(point);
          bMap.addOverlay(marker);
          // 逆地址编码
          getGeoCoder(point2, point1)
        } else {
          console.error('Map element is not found');
        }
      }

    }).catch((err) => {
      console.log(err)
    })
}
const onClickLeft = () => {
  router.push('/declare')
}
// 逆地址解码
const getGeoCoder = (point1, point2) => {
  var geoc = new BMapGL.Geocoder();
  var point = new BMapGL.Point(point1, point2);
  geoc.getLocation(point, (result) => {
    console.log(result)
    if (result) {
      const province = result.addressComponents.province;  // 省
      const city = result.addressComponents.city;          // 市
      const district = result.addressComponents.district;  // 区
      const street = result.addressComponents.street;      // 街道
      position.value = {
        province,
        city,
        district,
        street,
        rectangle: point1 + ',' + point2
      }
      console.log(position.value);
      console.log(`省市区: ${province}-${city}-${district}`);

    }
  }, {
    poiRadius: 1000  // 搜索周边POI的范围（米）
  });
}

const formData = reactive({
  location_info: '',
  report_desc: desc,
  contact_info: phone,
  // is_intervened: computed(() => into.value === 1)
});


const submitForm = async () => {
  try {
    // 组织位置信息
    if(position.value) {
      formData.location_info = `${position.value.province}${position.value.city}${position.value.district}${position.value.street}`;
    }

    // 发送POST请求
    const response = await fetch('http://localhost:8080/api/reports', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        location_info: formData.location_info,
        report_desc: desc.value,
        contact_info: phone.value,
        is_intervened: into.value === 1
      })
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    console.log('提交成功');
    // 清空表单
    desc.value = '';
    phone.value = '';
    into.value = 1;
    
    // 跳转回申报列表
    router.push('/declare');
    
  } catch (error) {
    console.error('提交失败:', error);
    // 可以添加错误提示
    alert('提交失败，请重试');
  }
};
</script>
<template>
  <div class=''>
    <div class=''>
      <van-nav-bar title="进行申报" left-text="返回"
                   left-arrow
                   @click-left="onClickLeft"  style="position: fixed; width: 100%; z-index: 999;" />
      <div class="container" ref="map"></div>
      <van-divider>当前位置</van-divider>
      <div v-if="position">
        <van-cell-group title="定位信息">
          <van-cell center title="省"
                    :value="position?.province" />
          <van-cell center title="市"
                    :value="position?.city" />
          <van-cell center title="区"
                    :value="position?.district" />
          <van-cell center title="详细地址"
                    :value="position?.street" />
          <van-cell center title="定位坐标"
                    :value="position?.rectangle" />
        </van-cell-group>
      </div>

      <van-cell-group inset>
        <van-field v-model="desc" name="username"
                   label="申报描述" type="textarea"
                   placeholder="申报描述" rows="6" />
        <van-field v-model="phone" name="phone"
                   label="联系方式"
                   placeholder="联系方式" />
        <van-field input-align="left"
                   label="是否有关部门介入" type="text"
                   readonly>
          <template #button>
            <van-radio-group v-model="into"
                             name="into"
                             direction="horizontal"
                             inset>
              <van-radio :name="1">是</van-radio>
              <van-radio :name="2">否</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-button type="primary"
                    block @click="submitForm">提交</van-button>
      </van-cell-group>

    </div>
  </div>
</template>

<style  scoped>
.container {
  width: 100vw;
  height: 400px;
}
</style>